package com.gjy.concurrency.cf;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

/**
 * @author 宫静雨
 * @version 1.0
 * @since 2023-03-22 13:52:32
 */
public class Shop {

    public double getPrice(String product) throws Exception {
        TimeUnit.SECONDS.sleep(1);
        ThreadLocalRandom current = ThreadLocalRandom.current();
        return current.nextInt() * product.charAt(0) + product.charAt(1);
    }

    public Future<Double> getPriceAsync(String product) {
        CompletableFuture<Double> cf = new CompletableFuture<>();
        new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            ThreadLocalRandom current = ThreadLocalRandom.current();
            double r = current.nextInt() * product.charAt(0) + product.charAt(1);
            cf.complete(r);
        }).start();
        return cf;
    }
}
